﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace ZapHelper
{
    /// <summary>
    /// Html's "a" tag and "href" attribute
    /// category parser
    /// </summary>
    /// <example>
    /// <a href="google.com">גוגל</a>
    /// </example>
    public class AHrefCategoryParser : CategoryParser
    {

        #region Constants

        private static String ATTRIBUTE_HREF = "href";

        #endregion

        protected override IEnumerable<Category> ParseCaterories()
        {

            var document = this.Document;

            // Select All of the <a> nodes.
            var nodes =
                document.DocumentNode.SelectNodes("//a");

            if (nodes == null)
            {
                throw new ParseFailedException("Cant parse this uri using this method.");
            }

            foreach (var node in nodes)
            {
                // Check that the current node is a relevant node
                // TODO: figure the rules

                var hrefAttribute = node.Attributes.Where(x => x.Name.Equals(ATTRIBUTE_HREF, StringComparison.CurrentCultureIgnoreCase)).SingleOrDefault();

                if (hrefAttribute == null)
                {
                    continue;
                }

                var categoryName = node.InnerText;
                var categoryUrl = hrefAttribute.Value;

                if (String.IsNullOrWhiteSpace(categoryName) || String.IsNullOrWhiteSpace(categoryUrl))
                {
                    continue;
                }

                // Trim vars
                categoryName =
                    Utils.TrimQuoteMarksAndDecodeHtml(categoryName);

                categoryUrl =
                    Utils.TrimQuoteMarksAndDecodeHtml(categoryUrl);

                // Recheck after trimming
                if (String.IsNullOrWhiteSpace(categoryName) || String.IsNullOrWhiteSpace(categoryUrl))
                {
                    continue;
                }

                Uri uri;
                try
                {
                    uri =
                        Utils.CreateReferenceUri(this.CategoriesUri, categoryUrl);
                }
                catch
                {
                    // Ignored purposely   
                    continue;
                }

                var category = new Category()
                {
                    Name = categoryName,
                    ProductsUri = uri
                };

                yield return category;

            }


        }

    }
}
